#!/usr/bin/python

import sys,re,datetime,common.db
from logging import *

monitor_type = 5

def register_minute(datetime1,datetime2):
    conn_web = common.db.connect('DMZwebDB')
    cursor_web = conn_web.cursor()
    
    minute1 = datetime1.strftime('%Y-%m-%d %H:%M')
    minute2 = datetime2.strftime('%Y-%m-%d %H:%M')

    delete_sql = "delete from dmz_gm.monitordata where StatTime between '%s:00' and '%s:59' and MonitorType=%d" % (minute1,minute2,monitor_type)
    cursor_web.execute(delete_sql)

    dt=datetime1.replace(day=1,hour=0,minute=0,second=0,microsecond=0)
    while dt<=datetime2:
        month_number  = dt.strftime('%Y%m');
        insert_sql = """insert into dmz_gm.monitordata (StatTime,ZoneID,MonitorType,MonitorData)
        select date_format(time,'%%Y-%%m-%%d %%H:%%i:00') minute,0,%d,count(*) 
        from dmz_log.log_register_%s 
        where time BETWEEN '%s:00' AND '%s:59'
        group by minute""" % (monitor_type,month_number,minute1,minute2)
        cursor_web.execute(insert_sql)

        dt=dt.replace(month=dt.month+1)

    conn_web.commit()
    cursor_web.close()
    conn_web.close()

if __name__ != "__main__":
    def arg_exit(tip=''):
        sys.exit(tip+('\nusage:\n\tpython %s %s [Y-m-d H:M] [Y-m-d H:M]' % (sys.argv[0],sys.argv[1])))

    argc=len(sys.argv)
    if argc==2 or argc==4 or argc==6:
        if argc==2:
            datetime1=datetime2=datetime.datetime.now()-datetime.timedelta(seconds=60)
        else:
            try:
                datetime1=datetime.datetime(*time.strptime(sys.argv[2]+' '+sys.argv[3],'%Y-%m-%d %H:%M')[0:5])
                if argc==4:
                    datetime2=datetime1
                else:
                    datetime2=datetime.datetime(*time.strptime(sys.argv[4]+' '+sys.argv[5],'%Y-%m-%d %H:%M')[0:5])
            except ValueError,msg:
                arg_exit(str(msg))
    else:
        arg_exit('argument count error')

    register_minute(datetime1,datetime2)


